﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.ServiceModel.Dispatcher;
using System.Text;
using System.ServiceModel.Description;
using log4net;

namespace NhJump.Persistence.Context.WcfBinding
{
    /// <summary>
    /// Automatically builds a persistence context when a WCF service is invoked
    /// </summary>
    public class UnitOfWorkAttribute : Attribute, IServiceBehavior
    {
        private static readonly ILog Log = LogManager.GetLogger(typeof(UnitOfWorkAttribute));

        public void Validate(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)
        {
        }

        public void AddBindingParameters(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase, Collection<ServiceEndpoint> endpoints, BindingParameterCollection bindingParameters)
        {
        }

        public void ApplyDispatchBehavior(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)
        {
            Log.DebugFormat("In ApplyDispatchBehavior, service type: {0}", serviceDescription.ServiceType);
            foreach (ChannelDispatcher channelDispatcher in serviceHostBase.ChannelDispatchers)
            {
                foreach (var endpoint in channelDispatcher.Endpoints)
                {
                    endpoint.DispatchRuntime.MessageInspectors.Add(new WcfUnitOfWorkMessageInspector(serviceDescription.ServiceType));
                }

                channelDispatcher.ErrorHandlers.Add(new WcfUnitOfWorkErrorHandler());
            }

        }
    }
}